package cn.antblog.base.jdkproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author yangjy
 * @version 1.0
 * @description: 测试
 * @date 2022/4/20 11:03
 */
public class TestProxy {
    public static void main(String[] args) {
        //1. 创建原始对象
        TestService testService = new TestServiceImpl();
        //2. 创建JDK动态代理
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("------proxy  log  before --------");
                //原始方法运行
                Object ret = method.invoke(testService, args);
                System.out.println("------proxy  log  after --------");
                return ret;
            }
        };

        /*
          ClassLoader loader,借用一个类加载器 创建代理类的class对象  ，进而可以创建代理对象
          Class<?>[] interfaces,
          InvocationHandler h
         */
        TestService testServiceProxy = (TestService) Proxy.newProxyInstance(TestServiceImpl.class.getClassLoader(), testService.getClass().getInterfaces(), handler);
        testServiceProxy.login("123", "123");
    }

//    public static void main(String[] args) {
//        TestService testService = new TestServiceImpl();
//
//        TestServiceProxy testServiceHandler = new TestServiceProxy(testService);
//
//        TestService testServiceProxy = (TestService) Proxy.newProxyInstance(
//                testService.getClass().getClassLoader(),
//                testService.getClass().getInterfaces(),
//                testServiceHandler);
//
//        testServiceProxy.login("杨敬一", "123");
//    }

}
